package com.androturka;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;

public class ConfigurationSender {

	Context context;

	public ConfigurationSender(Context context) {
		this.context = context;
	}

	public void sendConfiguration() throws ClientProtocolException, IOException {
		ConfigurationManager configurationManager = new ConfigurationManager(
				context);
		BufferedReader in = null;
		String deviceId = Secure.getString(context.getContentResolver(),
				Secure.ANDROID_ID);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		String registrationId = prefs.getString("REGISTRATIONID", null);
		if (registrationId != null) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet();
				try {
					// request.setURI(new
					// URI("http://depremgunlugu.com/register.php?deviceid="+URLEncoder.encode(deviceId)+"&registrationid="+URLEncoder.encode(registrationId).toString()));
					// request.setURI(new
					// URI("http://depremgunlugu.com/register.php?deviceid="+URLEncoder.encode(deviceId)+"&registrationid="+URLEncoder.encode(registrationId).toString()+configurationManager.getFilterURL()));
					request.setURI(new URI(WebAdapter.NAMESPACE
							+ "/register.php?deviceid="
							+ URLEncoder.encode(deviceId) + "&registrationid="
							+ URLEncoder.encode(registrationId).toString()
							+ configurationManager.getFilterURL()));
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
				HttpResponse response = client.execute(request);
				in = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent()));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				in.close();

				// String page = sb.toString();
				// System.out.println(page);
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		configurationManager.cleanup();
	}

}
